<?php
/**
 * svn log -r revision svn://ip/path --username user --password pass
 * @author Alan.H
 */
require_once dirname(__FILE__) ."/../Command.php";

class Log extends Command {
    /**
     * @var null
     */
    protected $revision = null;

    /**
     * @param $revision
     * @return $this
     */
    public function setRevision($revision) {
        $this->revision = $revision;
        return $this;
    }

    /**
     * @return $this|mixed
     */
    public function execCmd() {
        if ( ! $this->revision) {
            throw new InvalidArgumentException('Revision is empty!');
        }

        $cmd = [
            'svn',
            'log',
            '-r',
            is_array($this->revision) ? join(':', $this->revision) : $this->revision,
            '-v',
            $this->log->getUrl(),
            '--username',
            $this->log->getUsername(),
            '--password',
            $this->log->getPassword(),
        ];

        $name  = md5(join('', $cmd));
        $file  = $this->log->getRuntime() . '/' . $name . '.xml';
        $cmd[] = '--xml';
        $cmd[] = '>';
        $cmd[] = $file;

        if ( ! file_exists($file)) {
            exec(join(' ', $cmd));
        }

        $xml = simplexml_load_file($file);
        $this->parseXml($xml);

        $this->file = $file;
        return $this;
    }

    /**
     * @param $xml
     */
    public function parseXml($xml) {
        foreach ($xml->logentry as $logentry) {
            $revision = (string)$logentry['revision'];

            $entry = array();
            $entry['revision']  = $revision;
            $entry['author']    = (string)$logentry->author;
            $entry['date']      = $this->formatDate((string)$logentry->date);
            $entry['msg']       = (string)$logentry->msg;

            $actions = array();
            foreach ($logentry->paths->path as $path) {
                $actions[] = (string)$path['action'];
                $entry['paths'][md5((string)$path)] = array(
                    'action'=> (string)$path['action'],
                    'prop'  => (string)$path['prop-mods'],
                    'txt'   => (string)$path['text-mods'],
                    'kind'  => (string)$path['kind'],
                    'path'  => (string)$path
                );
            }
            $entry['actions'] = array_unique($actions);

            $this->setParam($revision, $entry);
        }
    }
}